"""This module provides zhuhu small"""
import json
import os
import time
import platform
from playwright.sync_api import sync_playwright
from playwright.sync_api import Page
#from pythonTryEverything.putdonwphone.data import englisword
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
########################################################################
class CMyZhiHu:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """
    def __init__(self,cookies_path: str, login_url: str, upload_picture_url: str, upload_mp4_url: str):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_picture_url = upload_picture_url
        self.upload_mp4_url = upload_mp4_url
        # playwright 部分
        self.browser = None
        # 想法 ---喜欢
        self.user_list = None
        self.context = None
        print("create CMyZhiHu")

    def __del__(self):
        print("CMyZhiHu is being destroyed")

    def upload_picture(self, picture_path_list: str, habit_name:str, habit_detail:str):
        """
          upload_picture
        """
        with sync_playwright() as playwright:
            display_headless = False
            sys = platform.system()
            if sys == "Linux":
              display_headless = True
              self.browser = playwright.chromium.launch(headless=display_headless)
            else:
                self.browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
            login_page = self.login_or_restore_cookies()
            print("login_or_restore_cookies")
            self.msg_up_load(login_page, picture_path_list, habit_name,habit_detail)
            self.browser.close()
    
    def upload_mp4(self, mp4_path: str,artile_title:str, msg: str):
        """
          upload_mp4
        """
        with sync_playwright() as playwright:
            display_headless = False
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
            self.browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
            login_page = self.login_or_restore_cookies()
            self.msg_up_load_mp4(login_page, mp4_path, artile_title,msg)
            self.browser.close()
        
    def login_or_restore_cookies(self) -> Page:
        """
          登录
        """
        userAgent ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            userAgent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
        
        self.context = self.browser.new_context(user_agent=userAgent)
        self.context.clear_cookies()
        page = self.context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            print("load cookies")
            # 从文件中加载 cookies
            with open(self.cookies_path, 'r',encoding='utf-8') as f:
                cookies = json.load(f)
            self.context.add_cookies(cookies)
            time.sleep(3)
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            time.sleep(30)
            cookies = page.context.cookies()
            with open(self.cookies_path, 'w',encoding='utf-8') as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page
   
    def msg_up_load_mp4(self, page: Page, mp4_file_path: str,artile_title:str, msg: str):
        """
        msg_up_load_mp4
        """
        page.goto(self.upload_mp4_url)
        page.wait_for_timeout(500)
        print(f"open  {self.upload_mp4_url}")
        
         # 点击选择文件，输入文件
        with page.expect_file_chooser() as fc_info:
            page.locator("xpath=//button[contains(text(), '上传视频')]").click()
        file_chooser = fc_info.value
        file_chooser.set_files(mp4_file_path)
        if platform.system() == "Windows":
           page.wait_for_timeout(120*1000)
        else:
          page.wait_for_timeout(20*1000)
        print("上传视频完成")
        ## https://www.zhihu.com/zvideo/upload-video

        page.mouse.down()
        page.mouse.down()
        #<input class="Input i7cW1UcwT6ThdhTakqFm" placeholder="输入视频标题" value="">
        #https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input
        page.get_by_placeholder("输入视频标题").fill(artile_title)
        page.mouse.down()
        page.wait_for_timeout(500)
        
        #<textarea rows="4" class="Input i7cW1UcwT6ThdhTakqFm" 
        # placeholder="填写视频简介，让更多人找到你的视频"></textarea>
        page.get_by_placeholder("填写视频简介，让更多人找到你的视频").fill(msg)
        page.mouse.down()
        page.wait_for_timeout(500)

        # 单选框
        # <input class="RadioButton-input css-1i5t6yb" type="radio" value="">
        #  https://developer.mozilla.org/en-US/play
        page.locator("css=.RadioButton.VideoUploadForm-radio.css-1u1atbi").locator('nth=0').click()
        page.wait_for_timeout(2*1000)
        # # 发布
        page.get_by_role("button", name="发布视频").click()
        print("点击发布视频")
        page.wait_for_timeout(8*1000)
        
    def auto_help_answer(self, page: Page, picture_path_list,habit_name:str, habit_detail:str):
        """
        msg_up_load
        """
        page.goto(self.upload_picture_url)
        time.sleep(6)
        print(f"open  {self.upload_picture_url}")
        # 从主页进入 headless不行
        page.locator("xpath=//div[contains(text(), '写想法')]").click()
        print("点击 发布图文")
        # time.sleep(3)
        # print(page.content)
        
        # # https://www.zhihu.com/creator
        # page.mouse.click(200,200)
        # dropdown = page.get_by_text("内容创作")
        # dropdown.hover()
        # # dropdown.locator('.dropdown__link >> text=python').click()
        # #dropdown.get_by_role("listitem").filter(has_text="python").click()
        # # 对于ul-li的元素，可以用listitem 的角色定位方式
        # page.locator("a").filter(has_text="发布想法").click()
        
        
        time.sleep(2)
        
        page.get_by_placeholder("请输入标题（选填）").fill(habit_name)
        page.get_by_role("textbox").locator('nth=-1').fill(habit_detail)
        # page.locator(".InputLike").fill(habit_detail)
        time.sleep(3)
        
        print("开始上传图片")
        page.locator(".css-88f71l > button:nth-child(2)").click()
        time.sleep(2)
        print("本地上传")
        with page.expect_file_chooser() as fc_info:
            page.locator(".css-n71hcb").click()
        file_chooser = fc_info.value
        file_chooser.set_files(picture_path_list)
        time.sleep(5)
       
        
        page.get_by_role("button", name="插入图片").click()
        time.sleep(5)
        
        print("结束上传图片")
        
        page.get_by_role("button", name="发布").click()
        print("发布")
        time.sleep(5)

    #################################################################################
    def zhihu_auto_guanzhu(self, page: Page):
        """
         赞同 三个积分 playwright codegen https://www.zhihu.com/creator
         follow ---
        """
        try:
            page.goto("https://www.zhihu.com/creator")
            time.sleep(5)
            page.mouse.down()
            page.get_by_role("button", name="去完成").nth(2).click()
            time.sleep(4)
            page.locator(".css-yxuzwv").first.click()
            page.mouse.down()
        finally:
            print("-----")
    ###############################


####################################################

def interface_auo_upload_mp4_zhihu(mp4_file_path,artile_title,artile_content):
    """
      对外调用接口
    """
    print("interface_auo_upload_mp4_zhihu")
    
    sys = platform.system()
    login_url = "https://www.zhihu.com/"
    upload_picture_url = "https://www.zhihu.com/"
    upload_mp4_url = "https://www.zhihu.com/zvideo/upload-video"
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\zhihu_small.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/zhihu_small.json"
    else:
        cookies_path = r"/root/bin/zhihu_small.json"

    autoupload = CMyZhiHu(cookies_path, login_url, upload_picture_url,upload_mp4_url)
    # 优化标题：
    if len(artile_title) == 0:
        artile_title = os.path.basename(mp4_file_path)
        artile_title = artile_title.split('.')[0]
    
    artile_content += "#日拱一卒无有尽，功不唐捐终入海" + "\r\n"
    autoupload.upload_mp4(mp4_file_path,artile_title, artile_content)
###############################################################
if __name__ == '__main__':
    # 自动发表mp4内容
    local_file_path= r"/Users/wangchuanyi/mp4/book/01.mp4"
    artile_title = "《掌控习惯》如何养成好习惯并戒除坏习惯"
    artile_content = "《掌控习惯》是一部系统且深入教授人们如何养成好习惯、戒除坏习惯的行动指南书"
    interface_auo_upload_mp4_zhihu(local_file_path,artile_title,artile_content)
